// src/components/RecursiveTreeView.js

// material-ui
import { TreeItem, TreeView } from '@mui/lab';
import React, { useState, useContext } from 'react'; // 添加useState
import Switch from '@mui/material/Switch';
// assets
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';

// 数据示例
const data = {
  id: 'root',
  name: '父节点1',
  children: [
    {
      id: '1',
      name: '一号节点'
    },
    {
      id: '3',
      name: '二号节点',
      children: [
        {
          id: '4',
          name: '三号节点'
        }
      ]
    }
  ]
};

// 递归树视图组件
const RecursiveTreeView = ({ options = data, selectOption }) => {
  // 添加一个状态来控制是否显示中文
  const [showChinese, setShowChinese] = useState(false); // true表示显示中文，false表示显示英文

  // 添加一个函数来处理语言切换
  const handleLanguageSwitch = () => {
    setShowChinese(!showChinese);
  };

  // 修改的部分：在 handleTreeItemClick 函数中，根据 showChinese 状态来决定使用哪个名称
  const handleTreeItemClick = (event, label, path) => {
    event.stopPropagation();
    selectOption(label, path);
  };

  // 修改的部分：在 renderTree 函数中，根据 showChinese 状态来决定使用哪个名称
  const renderTree = (nodes, path = '') => {
    // const newPath = `${path}${nodes.name}`;
    const newPath = path ? `${path}.${nodes.name}` : nodes.name; // 调整了这里
    return (
      <TreeItem
        key={nodes.id}
        nodeId={nodes.id}
        label={
          // eslint-disable-next-line jsx-a11y/click-events-have-key-events
          <button
            type="button"
            onClick={(event) => handleTreeItemClick(event, showChinese ? nodes.labelCn : nodes.label, newPath)}
            onKeyPress={(event) => {
              if (event.key === 'Enter') {
                handleTreeItemClick(event, showChinese ? nodes.labelCn : nodes.label, newPath);
              }
            }}
            style={{ background: 'none', border: 'none', cursor: 'pointer' }}
          >
            {showChinese ? nodes.labelCn : nodes.label} {/* 使用新的label和labelCn */}
          </button>
        }
      >
        {Array.isArray(nodes.children) ? nodes.children.map((node, index) => renderTree(node, `${newPath}`)) : null}
      </TreeItem>
    );
  };

  return (
    <>
      {/* 添加一个开关按钮来控制语言切换 */}
      <div style={{ display: 'block', alignItems: 'center' }}>
        <span>{showChinese ? '原文' : '翻译'}</span> {/* 根据 showChinese 状态显示不同的文字 */}
        <Switch onClick={handleLanguageSwitch} />
      </div>
      <TreeView defaultCollapseIcon={<ExpandMoreIcon />} defaultExpanded={['root']} defaultExpandIcon={<ChevronRightIcon />}>
        {renderTree(options)}
      </TreeView>
    </>
  );
};

export default RecursiveTreeView;
